package storage

import (
	"fmt"
	"time"

	"new_sensitive/internal/model"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

// MySQLStorage MySQL存储实现
type MySQLStorage struct {
	db *sqlx.DB
}

// NewMySQLStorage 创建MySQL存储实例
func NewMySQLStorage(host string, port int, username, password, dbname, charset string) (*MySQLStorage, error) {
	// 构建DSN连接字符串
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=true",
		username, password, host, port, dbname, charset)

	// 连接数据库
	db, err := sqlx.Connect("mysql", dsn)
	if err != nil {
		return nil, fmt.Errorf("连接MySQL失败: %v", err)
	}

	// 设置连接池参数
	db.SetMaxOpenConns(20)
	db.SetMaxIdleConns(10)
	db.SetConnMaxLifetime(time.Hour)

	return &MySQLStorage{db: db}, nil
}

// GetAllSensitiveWords 获取所有敏感词
func (s *MySQLStorage) GetAllSensitiveWords() ([]model.SensitiveWord, error) {
	var words []model.SensitiveWord
	query := "SELECT badid, typename, badword, level, replaceword, lastusetime, listorder FROM t_badword"

	err := s.db.Select(&words, query)
	if err != nil {
		return nil, fmt.Errorf("查询敏感词失败: %v", err)
	}

	return words, nil
}

// AddSensitiveWord 添加敏感词
func (s *MySQLStorage) AddSensitiveWord(word model.SensitiveWord) error {
	query := `
		INSERT INTO t_badword (badword, typename, level, replaceword, lastusetime, listorder)
		VALUES (?, ?, ?, ?, ?, ?)
	`

	_, err := s.db.Exec(query, word.BadWord, word.TypeName, word.Level, word.ReplaceWord, word.LastUseTime, word.ListOrder)
	if err != nil {
		return fmt.Errorf("添加敏感词失败: %v", err)
	}

	return nil
}

// UpdateSensitiveWord 更新敏感词
func (s *MySQLStorage) UpdateSensitiveWord(word model.SensitiveWord) error {
	query := `
		UPDATE t_badword
		SET badword = ?, typename = ?, level = ?, replaceword = ?, lastusetime = ?, listorder = ?
		WHERE badid = ?
	`

	result, err := s.db.Exec(query, word.BadWord, word.TypeName, word.Level, word.ReplaceWord, word.LastUseTime, word.ListOrder, word.BadID)
	if err != nil {
		return fmt.Errorf("更新敏感词失败: %v", err)
	}

	affected, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("获取影响行数失败: %v", err)
	}

	if affected == 0 {
		return fmt.Errorf("未找到ID为%d的敏感词", word.BadID)
	}

	return nil
}

// DeleteSensitiveWord 删除敏感词
func (s *MySQLStorage) DeleteSensitiveWord(id int64) error {
	query := "DELETE FROM t_badword WHERE badid = ?"

	result, err := s.db.Exec(query, id)
	if err != nil {
		return fmt.Errorf("删除敏感词失败: %v", err)
	}

	affected, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("获取影响行数失败: %v", err)
	}

	if affected == 0 {
		return fmt.Errorf("未找到ID为%d的敏感词", id)
	}

	return nil
}

// Close 关闭数据库连接
func (s *MySQLStorage) Close() error {
	return s.db.Close()
}
